/**
 * Created by huangzx on 2015/12/7.
 */
define( ['angular',
        'framework/msg/GillionMsgModule',
        'framework/associate/GillionAssociateModule',
        'framework/dataGrid/DataGridModule',
        'framework/pagination/GillionPaginationModule',
        'system2/RuleStatusModule',
        'system2/RulePermissionModule'],
function (angular) {
    var app = angular.module('ConditionModule', ['GillionMsgModule', 'GillionAssociateModule', 'DataGridModule', 'GillionPaginationModule','RuleStatusModule','RulePermissionModule']);
    app.controller('ConditionController', ['$scope', '$http', '$compile', '$timeout', 'GillionMsgService', 'Resource', 'Arrays', function ($scope, $http, $compile, $timeout,GillionMsgService, Resource, Arrays) {
        var data = GillionMsgService.getInputData();
        $scope.count=1;
        $scope.countCondition=1;
        $scope.nowClick = 1;
        $scope.jsonContext={};
        $scope.showSign=false;
        $scope.showProperty=false;
        $scope.showEntry=false;
        $scope.showNone=true;
        $scope.showAllCondition=false;
        $scope.showMethod=false;
        $scope.translate=[{">":"大于"},{">=":"大于等于"},{"==":"等于"},{"<":"小于"},{"<=":"小于等于"},{"!=":"不等于"},{"+":"加"},
            {"-":"减"},{"*":"乘"},{"/":"除"},{"(":"("},{")":")"}];
        $scope.conditionRows=[];
        $scope.conditions=[];
        $scope.status=data.status;
        $scope.packageId=data.packageId;
        $timeout(function(){
            if (data.treeNode.conditions && data.treeNode.conditions!='{}') {
                $scope.context = data.treeNode.conditions;
                var json = eval('(' + $scope.context + ')');
                var resultList = showRule(json);
                setHtml(resultList);
            }
        });

        function showRule(json){
            var resultList=[];
            if(json.type=="parenthesis"){
                resultList = resultList.concat({'oper':'('});
                resultList = resultList.concat(showRule(json.expression));
                resultList = resultList.concat({'oper':')'});
            }else if(json.type=="lastDateTime"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'lastDateTime','source':'{}'});
            }else if(json.type=="addHours"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'addHours','source':'{}','hours':json.hours});
            }else if(json.type=="countHours"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'countHours','source':'{}','hours':json.hours});
            }else if(json.type=="endsWith"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'endsWith','source':'{}','str':json.str});
            }else if(json.type=="startWith"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'startWith','source':'{}','str':json.str});
            }else if(json.type=="matchWith"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'matchWith','source':'{}','str':json.str});
            }else if(json.type=="matcher"){
                resultList = resultList.concat(showRule(json.source));
                resultList = resultList.concat( {'type':'matcher','source':'{}','str':json.str});
            }else if(json.type=="remoteService"){
                resultList = resultList.concat({'type':'remoteService'});
                resultList = resultList.concat(showRule(json.serviceCode));
                for(var i=0;i<json.params.length;i++){
                    resultList = resultList.concat(showRule(json.params[i]));
                }
            }else if(json.type=="JDBCService"){
                resultList = resultList.concat({'type':'JDBCService'});
                resultList = resultList.concat(showRule(json.sqlName));
                for(var i=0;i<json.params.length;i++){
                    resultList = resultList.concat(showRule(json.params[i]));
                }
            }else if(json.type=="Dubbo"){
                resultList = resultList.concat({'type':'Dubbo'});
                resultList = resultList.concat(showRule(json.dubboName));
                for(var i=0;i<json.params.length;i++){
                    resultList = resultList.concat(showRule(json.params[i]));
                }
            }else if(json.type=="MapPut"){
                resultList = resultList.concat({'type':'MapPut'});
                resultList = resultList.concat(showRule(json.map));
                resultList = resultList.concat(showRule(json.key));
                resultList = resultList.concat(showRule(json.value));
            }else if(json.type=="MapGet"){
                resultList = resultList.concat({'type':'MapGet'});
                resultList = resultList.concat(showRule(json.map));
                resultList = resultList.concat(showRule(json.key));
            }else if(json.type=="ListAdd"){
                resultList = resultList.concat({'type':'ListAdd'});
                resultList = resultList.concat(showRule(json.list));
                resultList = resultList.concat(showRule(json.value));
            }else if(json.type=="MAX"||json.type=="MIN"||json.type=="AVG"||json.type=="SUM"){
                resultList = resultList.concat({'type':json.type});
                for(var i=0;i<json.params.length;i++){
                    resultList = resultList.concat(showRule(json.params[i]));
                }
            }else if(json.type=="Rule"){
                resultList = resultList.concat({'type':'Rule'});
                resultList = resultList.concat(showRule(json.groupId));
                resultList = resultList.concat(showRule(json.artifactId));
                for(var i=0;i<json.params.length;i++){
                    resultList = resultList.concat(showRule(json.params[i]));
                }
            }else if(json.type=="Rate"){
                resultList = resultList.concat({'type':'Rate'});
                resultList = resultList.concat(showRule(json.RateValue));
                resultList = resultList.concat(showRule(json.Rate));
                if(json.countValue!=null){
                    resultList = resultList.concat(showRule(json.countValue));
                }
            }else {
                if (json.left != null || json.right != null) {
                    resultList = resultList.concat(showRule(json.left));
                    resultList = resultList.concat({'oper':json.oper});
                    resultList = resultList.concat(showRule(json.right));
                } else {
                    resultList.push(json);
                }
            }
            return resultList;
        }

        function setHtml(list,type) {
            var conditionList =[];
            var thenList=[];
            if (type == 'condition'){
                if (list.length > 0) {
                    $scope.addConditionRow("",conditionList);
                }
            }
            for(var i=0;i<list.length;i++){
                if(list[i].oper!="undefined"&&list[i].oper!=null&&list[i].oper!="&&"&&list[i].oper!="||") {
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var mes=translateMes(list[i].oper);
                    $scope.setConditionList(conditionList,mes,JSON.stringify(list[i]),'sign');

                }else if(list[i].type=="model"||list[i].type=="const"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var type;
                    if(list[i].type=="model"){
                        type="property";
                    }else{
                        type="entry";
                    }
                    $scope.setConditionList(conditionList,list[i].value==""?"\'\'":list[i].value,JSON.stringify(list[i]),type);

                }else if(list[i].type=="variable"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,list[i].variableName,JSON.stringify(list[i]),'variable');
                }else if(list[i].type=="listValue"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,"获取"+list[i].source,JSON.stringify(list[i]),'list');
                }else if(list[i].type=="nowDate"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,"当前时间",JSON.stringify(list[i]),'method');
                }else if(list[i].type=="lastDateTime"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,"当天最后时间",JSON.stringify(list[i]),'method');
                }else if(list[i].type=="addHours"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var mes
                    if(isNaN(list[i].hours)){
                        mes ="加 "+list[i].hours.value+" 小时";
                    }else{
                        mes ="加 "+list[i].hours+" 小时";
                    }
                    $scope.setConditionList(conditionList,mes,JSON.stringify(list[i]),'method');

                }else if(list[i].type=="countHours"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var mes
                    if(isNaN(list[i].hours)){
                        mes ="加 "+list[i].hours.value+" 小时";
                    }else{
                        mes ="加 "+list[i].hours+" 小时";
                    }
                    $scope.setConditionList(conditionList,mes,JSON.stringify(list[i]),'method');

                }else if(list[i].type=="startWith"||list[i].type=="endsWith"||list[i].type=="matchWith"||list[i].type=="matcher"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var mes
                    if(list[i].type=="startWith"){
                        mes ="以 "+list[i].str+" 开始";
                    }else if(list[i].type=="endsWith"){
                        mes ="以 "+list[i].str+" 结尾";
                    }else if(list[i].type=="matchWith"){
                        mes ="包含 "+list[i].str;
                    }else if(list[i].type=="matcher"){
                        mes ="匹配正则 "+list[i].str;
                    }
                    $scope.setConditionList(conditionList,mes,JSON.stringify(list[i]),'method');

                }else if(list[i].type=="compareHour"||list[i].type=="replaceDate"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var mes1,mes2,mes3,type1,type2,typeValue;
                    if(list[i].source.value==undefined){
                        mes1=list[i].source.variableName;
                        type1="variable";
                    }else{
                        mes1=list[i].source.value;
                        type1="property";
                    }
                    $scope.setConditionList(conditionList,mes1,JSON.stringify(list[i].source),type1);
                    $scope.nowClick++;
                    $scope.countCondition++;
                    if(list[i].type=="compareHour"){
                        mes2="小时比较";
                        typeValue="{'type':'compareHour'}";
                    }else{
                        mes2 = "替换时分秒";
                        typeValue="{'type':'replaceDate'}";
                    }
                    $scope.setConditionList(conditionList,mes2,typeValue,'method');
                    $scope.nowClick++;
                    $scope.countCondition++;
                    mes3=list[i].hours.value;

                    if(list[i].hours.value===undefined){
                        mes3=list[i].hours.variableName;
                        type2="variable";
                    }else{
                        mes3=list[i].hours.value;
                        type2="property";
                    }
                    $scope.setConditionList(conditionList,mes3,JSON.stringify(list[i].hours),type2);
                }else if(list[i].type=="remoteService"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,'远程服务',JSON.stringify(list[i]),'component');

                }else if(list[i].type=="JDBCService"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,'数据库组件',JSON.stringify(list[i]),'component');

                }else if(list[i].type=="Dubbo"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,'Dubbo服务',JSON.stringify(list[i]),'component');

                }else if(list[i].type=="MapPut"||list[i].type=="MapGet"||list[i].type=="ListAdd"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var convergeStr;
                    if(list[i].type=="MapPut"){
                        convergeStr="Map设置";
                    }else if(list[i].type=="MapGet"){
                        convergeStr="Map获取";
                    }else if(list[i].type=="ListAdd"){
                        convergeStr="List添加";
                    }
                    $scope.setConditionList(conditionList,convergeStr,JSON.stringify(list[i]),'component');

                }else if(list[i].type=="MAX"||list[i].type=="MIN"||list[i].type=="AVG"||list[i].type=="SUM"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    var convergeStr;
                    if(list[i].type=="MAX"){
                        convergeStr = "最大值";
                    }else if(list[i].type=="MIN"){
                        convergeStr = "最小值";
                    }else if(list[i].type=="AVG"){
                        convergeStr = "平均值";
                    }else if(list[i].type=="SUM"){
                        convergeStr = "求和";
                    }
                    $scope.setConditionList(conditionList,convergeStr,JSON.stringify(list[i]),'component');
                }else if(list[i].type=="Rule") {
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,'规则组件',JSON.stringify(list[i]),'component');

                }else if(list[i].type=="Rate") {
                    $scope.nowClick++;
                    $scope.countCondition++;
                    $scope.setConditionList(conditionList,'费率组件',JSON.stringify(list[i]),'component');
                }else if(list[i].oper=="&&"){
                    $scope.nowClick++;
                    $scope.countCondition++;
                    conditionList =[];
                    $scope.addConditionRow("&&",conditionList,false);
                }else if(list[i].oper=="||"){
                    conditionList =[];
                    $scope.addConditionRow("||",conditionList,false);
                }else if(list[i].type=="setRtnValue"){
                    conditionList =[];
                    $scope.addThen("setRtnValue",conditionList,false);
                }else if(list[i].type=="throw"){
                    conditionList =[];
                    $scope.addThen("throw",conditionList,false);
                    $scope.setConditionList(conditionList,list[i].code,"{'type':'const'}",'entry');
                } else if(list[i].type=="execute"){
                    conditionList =[];
                    $scope.addThen("execute",conditionList,false);
                    if(list[i].code=="list"){
                        $scope.setConditionList(conditionList,"循环"+list[i].source.variableName,"{'type':'list','listSource':'"+list[i].source.variableName+"'}",'list')
                    }else if(list[i].code=="listEnd"){
                        $scope.setConditionList(conditionList,"循环结束","{'type':'listEnd'}",'list')

                    }else if(list[i].code=="judgeEnd"){
                        $scope.setConditionList(conditionList,"判断结束","{'type':'judgeEnd'}",'list')

                    }else if(list[i].code=="judge"){
                        $scope.setConditionList(conditionList,"判断","{'type':'judge'}",'list')
                    }else{
                        //其他情况，code为null  目前仅有map操作
                        //$scope.setConditionList(conditionList,list[i].key,"{'type':'variable','variableName':'"+list[i].key+"'}",'variable')
                    }

                }else if(list[i].type=="setVariable"){
                    conditionList =[];
                    $scope.addThen("setVariable",conditionList,false);
                    $scope.setConditionList(conditionList,list[i].key,"{'type':'variable','variableName':'"+list[i].key+"'}",'variable')

                }else if(list[i].type=="setModel"){
                    conditionList =[];
                    $scope.addThen("setModel",conditionList,false);
                    $scope.setConditionList(conditionList,list[i].modelId,"{'type':'model','value':'"+list[i].modelId+"'}",'property')
                }else if(list[i].type=="breakPackage"||list[i].type=="breakAssembly"){
                    conditionList =[];
                    $scope.addThen(list[i].type,conditionList,false);
                }
            }
        }

        $scope.addConditionRow=function(type,conditionList,isButton){
            $scope.count++;
            $scope.countCondition++;
            init();
            $scope.conditionRows.push({
                _id: $scope.count,
                countCondition: $scope.countCondition,
                conditions:conditionList,
                sign:type,
                isButton:isButton
            });
            checkRule();
        };

        $scope.setConditionList = function(conditionList,mes,value,type){
            conditionList.push({
                countCondition: $scope.countCondition,
                mes:mes,
                value:value,
                type:type
            });
        }

        var childAttributeResource = Resource("/grule-manager/businessModelAttribute/childList/:id", {
            id: "@id"
        });

        //加载模型
        Resource("/grule-manager/businessModelAttribute/list/:id", {id: '@id'}).get({
            id:  data.modelId
        }, function (response) {
            if(response.data!=null){
                $scope.modelAttributes=response.data;
            }
        });
        //加载变量
        function loadVariables() {
            Resource("/grule-manager/variables/decisionTree/:id", {id: '@id'}).get({
                id:data.treeNode.treeId
            }, function (response) {
                if(response.data!=null){
                    $scope.variables=response.data;
                }
            });
        }
        loadVariables();

        angular.element(document).off('refresh.variables').on('refresh.variables', function() {
            loadVariables();
        });

        function init(){
            $scope.showNone=true;
            $scope.showSign=false;
            $scope.showProperty=false;
            $scope.showEntry=false;
            $scope.showAllCondition=false;

            $scope.showMethod=false;
            $scope.showComponent=false;
            $scope.showSpecial=false;

        }
        //isButton 是否需要显示按钮
        $scope.addRow=function(type,conditionList,isButton){
            $scope.count++;
            $scope.countCondition++;
            init();
            $scope.conditionRows.push({
                _id: $scope.count,
                countCondition: $scope.countCondition,
                conditions:conditionList,
                sign:type,
                isButton:isButton
            });
            //checkRule();
        };

        $scope.change=function (click){
            angular.element("#symbol" + click).parent().bind("mouseleave", function (){
                closeChange("symbol"+click);
            });
            var sign ;
            var mes;
            if(angular.element("#symbol"+click).text()=="或者") {
                sign="&&";
                mes="并且";
            }else if(angular.element("#symbol"+click).text()=="并且"){
                sign="||";
                mes="或者";
            }
            angular.element("#symbol" + click).after(
                $compile(
                    "<div class='also-open'>" +
                    "<div class='also-open-a'><a href='javascript:void(0)' ng-click='selectLogicalSign(&apos;"+sign+"&apos;,&apos;"+mes+"&apos;,&apos;"+click+"&apos;)'>"+mes+"</a></div>" +
                    "</div>"
                )($scope)
            )
        };
        function closeChange(click){
            var element = angular.element("#" + click).parent().children();
            for(var i=1;i<element.length;i++){
                element[i].remove();
            }
        }
        $scope.selectLogicalSign=function(sign,mes,num){
            $scope.count++;
            var node   = angular.element("#symbol" + num).parent().empty();
            node.append(
                $compile(
                    "<a href='javascript:void(0)' ng-click='change("+$scope.count+")' name='node'  id='symbol"+$scope.count+"' value='{&apos;oper&apos;:&apos;"+sign+"&apos;}'>"+mes+"<i class='icon-engine-down-a'></i></a>"
                )($scope)
            )
        };

        $scope.addCondition=function(count){
            $scope.countCondition++;
            init();
            angular.element("#addRow" + count).append(
                $compile(
                    "<span  id='click"+$scope.countCondition+"' ><button type='button' name ='addButton' id='showCondition"+$scope.countCondition+"' ng-click='show("+$scope.countCondition+",&apos;button&apos;)' class='engine-btn-default'>点击选择</button></span>"
                )($scope)
            );
        };

        $scope.removeCondition = function(num){
            angular.element("#click" + num).remove();
            //checkRule();
        };

        $scope.removeRowCondition=function(index){
            $scope.conditionRows.splice(index, 1);
        };

        $scope.show=function(type,model,showType){
            showDIV();
            var list = document.getElementsByName("column");
            for(var i=0; i< list.length; i++){
                list[i].className = "";
            }
            if(type=='sign'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=true;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
                $scope.showComponent=false;
                $scope.showSpecial=false;
            }else if(type=='entry'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=true;
                $scope.showVariable=false;
                $scope.showMethod=false;
                $scope.showComponent=false;
                $scope.showSpecial=false;
            }else if(type=='property'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=true;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
                $scope.showComponent=false;
                $scope.showSpecial=false;
            }else if (type=='variable'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=true;
                $scope.showMethod=false;
                $scope.showComponent=false;
                $scope.showSpecial=false;
            }else if (type=='method'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=true;
                $scope.showComponent=false;
                $scope.showSpecial=false;
            }else if (type=='component'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
                $scope.showComponent=true;
                $scope.showSpecial=false;
            }else if (type=='special'){
                document.getElementById(type).setAttribute("class","on");
                $scope.showNone=false;
                $scope.showAllCondition=true;
                $scope.showProperty=false;
                $scope.showSign=false;
                $scope.showEntry=false;
                $scope.showVariable=false;
                $scope.showMethod=false;
                $scope.showComponent=false;
                $scope.showSpecial=true;
            }else{
                $scope.nowClick = type;
                $scope.clickType=model;//记录按钮或者节点点击，判断是否添加条件选择按钮

                if(model=="button") {
                    var doc = angular.element("#showCondition" + $scope.nowClick);
                    //添加高亮样式
                    doc.addClass("attribute-check");
                    doc.text("右侧边栏选择");
                    showType="property";
                }else if(model=="node"){
                    var doc = angular.element("#node" + $scope.nowClick);
                    //添加高亮样式
                    doc.addClass("attribute-check");
                    closeEdit("node","edit");
                }
                $scope.show(showType);
            }
        };

        $scope.viewObject = function (id,margin) {
            if($("#"+id).text()=="对象[-]"){
                angular.element("#son"+id).text("");
                $("#"+id).text("对象[+]");
                return;
            }
            $("#"+id).text("对象[-]");
            childAttributeResource.get({
                id: id
            }, function (response) {
                if (response.success) {
                    var records = response.data;
                    angular.forEach(records, function (item){
                        if(item.dataType!='Object'){
                            angular.element("#son"+id).append(
                                $compile(
                                    "<div class='model-value model-value-son' style='margin-left:"+20*margin+"px'>"+
                                    "<div class='model-value-l'><button type='button' class='engine-btn-model' ng-click='addModel(&apos;"+item.name+"&apos;)'>"+item.dataType+"</button></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='clear'></div>"+
                                    "</div>"
                                )($scope)
                            )
                        }else{
                            angular.element("#son"+id).append(
                                $compile(
                                    "<div class='model-value model-value-son' style='margin-left:"+20*margin+"px'>"+
                                    "<div class='model-value-l'><button type='button' id='"+item.id+"' ng-click='viewObject(&apos;"+item.id+"&apos;,"+(margin+1)+")' class='engine-btn-model'>对象[+]</button></div>"+
                                    "<div class='model-value-r'>"+item.name+"</div>"+
                                    "<div class='clear'></div>"+
                                    "</div>"+
                                    "<div id='son"+item.id+"'></div>"
                                )($scope)
                            )
                        }
                    })
                }
            });
        };


        $scope.addButton= function(){

            $scope.countCondition++;
            if($scope.clickType=="button") {
                angular.element("#click" + $scope.nowClick).after(
                    $compile(
                        "<span class='attribute'  id='click" + $scope.countCondition + "' ><button type='button' name ='addButton' id='showCondition" +  $scope.countCondition + "' ng-click='show(" + $scope.countCondition + ",&apos;button&apos;)' class='engine-btn-default'>点击选择</button></span>"
                    )($scope)
                );
            }
        }

        $scope.addEntry=function(){
            var expression;
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            if($scope.textEntry=="\'\'"){
                expression = "{'type':'const','value':''}";
            }else{
                expression = "{'type':'const','value':'"+$scope.textEntry+"'}";
            }
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='javascript:void(0)' name='node' id='node"+$scope.nowClick+"' ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;,&apos;entry&apos;)' type='entry'      value="+expression+">"+$scope.textEntry+"</a>"
                )($scope)
            );
            afterAdd();
        };

        $scope.addSign=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            var mes=translateMes(value);
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='javascript:void(0)' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign'       value='{&apos;oper&apos;:&apos;"+value+"&apos;}'>"+mes+"</a>"
                )($scope)
            )
            afterAdd();
        };
        $scope.addModel=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='javascript:void(0)' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;,&apos;property&apos;)' type='property'      value='{&apos;type&apos;:&apos;model&apos;,&apos;value&apos;:&apos;"+value+"&apos;}'>"+value+"</a>"
                )($scope)
            )
            afterAdd();
        };

        $scope.addVariable=function(value){
            document.getElementById('click'+$scope.nowClick).setAttribute("class","attribute");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#click" + $scope.nowClick).html(
                $compile(
                    "<a href='javascript:void(0)' name='node'  id='node"+$scope.nowClick+"'  ng-click='show(&apos;"+$scope.nowClick+"&apos;,&apos;node&apos;,&apos;variable&apos;)' type='variable'       value='{&apos;type&apos;:&apos;variable&apos;,&apos;variableName&apos;:&apos;"+value+"&apos;}'>"+value+"</a>"
                )($scope)
            )
            afterAdd();
        };

        $scope.addMethod=function(value,text){
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");

            if(value=='addHours') {
                var hour = document.getElementById("addHours").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                if(isNaN(hour)){
                    expression="{'type':'"+value+"','source':'{}','hours':{'type':'model','value':'"+hour+"'}}";
                }else{
                    expression="{'type':'"+value+"','source':'{}','hours':'"+hour+"'}";
                }
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">加 " + hour + " 小时</a>"
                    )($scope)
                )
            }if(value=='countHours') {
                var hour = document.getElementById("countHours").value;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                var expression="{'type':'"+value+"','source':'{}','hours':'"+hour+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">加 " + hour + " 小时</a>"
                    )($scope)
                )
            }else if(value=='lastDateTime'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method'       value='{&apos;type&apos;:&apos;"+value+"&apos;,&apos;source&apos;:&apos;{}&apos;}'>"+text+"</a>"
                    )($scope)
                )
            }else if(value=='nowDate'||value=='compareHour'||value=='replaceDate'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value='{&apos;type&apos;:&apos;"+value+"&apos;}'>"+text+"</a>"
                    )($scope)
                )
            }else if(value=="remoteService"||value=="JDBCService"||value=='Rule'||value=='Rate'||value=='MAX'||value=='MIN'||value=='AVG'||value=='SUM'||value=='MapPut'||value=='MapGet'||value=='ListAdd'||value=='Dubbo'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;component&apos;)' type='component' value='{&apos;type&apos;:&apos;"+value+"&apos;}'>"+text+"</a>"
                    )($scope)
                )
            }else if(value=='startWith') {
                var str = document.getElementById("startWith").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','source':'{}','str':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">以 " + str + " 开始</a>"
                    )($scope)
                )
            }else if(value=='endsWith') {
                var str = document.getElementById("endsWith").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','source':'{}','str':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">以 " + str + " 结束</a>"
                    )($scope)
                )
            }else if(value=='matchWith') {
                var str = document.getElementById("matchWith").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','source':'{}','str':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">包含 " + str + "</a>"
                    )($scope)
                )
            }else if(value=='matcher') {
                var str = document.getElementById("matcher").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','source':'{}','str':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;method&apos;)' type='method' value="+expression+">匹配正则 " + str + "</a>"
                    )($scope)
                )
            }else if(value=='list'){
                var str = document.getElementById("loopList").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','listSource':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;list&apos;)' type='list' value="+expression+">循环 " + str + "</a>"
                    )($scope)
                )
            }else if(value=='listValue'){
                var str = document.getElementById("listValue").value;
                var expression;
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'"+value+"','source':'"+str+"'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;list&apos;)' type='list' value="+expression+">获取 " + str + "</a>"
                    )($scope)
                )
            }else if(value=='listEnd'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'listEnd'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;list&apos;)' type='list' value="+expression+"> 循环结束</a>"
                    )($scope)
                )
            }
            else if(value=='judge'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'judge','left':{},'right':{},'oper':''}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;list&apos;)' type='list' value="+expression+"> 判断</a>"
                    )($scope)
                )
            }
            else if(value=='judgeEnd'){
                document.getElementById('click' + $scope.nowClick).setAttribute("class", "attribute");
                expression="{'type':'judgeEnd'}";
                angular.element("#click" + $scope.nowClick).html(
                    $compile(
                        "<a href='javascript:void(0)' name='node'  id='node" + $scope.nowClick + "'  ng-click='show(&apos;" + $scope.nowClick + "&apos;,&apos;node&apos;,&apos;list&apos;)' type='list' value="+expression+"> 判断结束</a>"
                    )($scope)
                )
            }
            afterAdd();
        };

        function afterAdd(){
            angular.element("#click" + $scope.nowClick).bind("mouseleave", function (){
                closeEdit('node',"edit");
            });
            angular.element("#click" + $scope.nowClick).bind("mouseenter",function (){
                showEdit('node',"edit");
            });
            if(!$scope.showButton) {
                $scope.addButton();
            }
            $scope.showButton=false;
            closeDiv();
            init();
            checkRule();
        }

        $scope.addFront=function(value){
            showDIV();
            init();
            $scope.countCondition++;

            angular.element("#click" + value).before(
                $compile(
                    "<span  id='click" + $scope.countCondition + "' ><button type='button' id='showCondition" +  $scope.countCondition  + "' ng-click='show(&apos;" + $scope.countCondition + "&apos;,&apos;button&apos;)' class='engine-btn-default attribute-check'>右侧边栏选择</button></span>"
                )($scope)
            );
            $scope.showButton=true;  //控制是否带出按钮  ， 区分 前后编辑和 普通编辑的区别,前后编辑选中后不添加按钮
            $scope.show($scope.countCondition,"button","sign");

        };

        $scope.addBehind=function(value){
            showDIV();
            init();
            $scope.countCondition++;
            angular.element("#click" + value).after(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'><button type='button' id='showCondition" + $scope.countCondition  + "' ng-click='show(&apos;" + $scope.countCondition + "&apos;,&apos;button&apos;)' class='engine-btn-default attribute-check'>右侧边栏选择</button></span>"
                )($scope)
            );
            $scope.showButton=true;  //控制是否带出按钮  ， 区分 前后编辑和 普通编辑的区别
            $scope.show($scope.countCondition,"button","sign");
        };

        var TreeNodeResource = Resource("/grule-manager/decisionTreeNodes/:id", {
            id: "@id"
        });

        function cb(response){
            if(response.success){
                GillionMsgService.setOutputData({
                    success: true,
                    treeNode: response.data
                });
                GillionMsgService.close();
            }
        }

        $scope.save=function(){
            var list=[];
            var nodes = $("a[name='node']");
            angular.forEach(nodes,function(node){
                list.push( eval("(" + node.attributes.value.nodeValue + ")"));
            });
            var result = getResult(list);
            data.treeNode.conditions = JSON.stringify(result) || '';
            if (data.treeNode.id) {
                TreeNodeResource.update(data.treeNode, cb);
            } else {
                TreeNodeResource.create(data.treeNode, cb);
            }
        };


        function getResult(list){
            var resultList=[];
            resultList = handleParenthesis(list);
            resultList = outParenthesis(resultList);
            return resultList;
        }

        function handleParenthesis(list){
            var result=[];
            var resultList=[];
            var leftBrackets =[];
            var brackets=[];
            for(var i=0;i<list.length;i++){
                if(list[i].oper!=null&&list[i].oper=="("){
                    leftBrackets.push(i);
                }else if(list[i].oper!=null&&list[i].oper==")"){
                    var model = {};
                    model.left = leftBrackets.pop();
                    model.right = i;
                    brackets.push(model);
                }
            }
            if(brackets.length>0) {
                for (var i = 0; i < list.length; i++) {
                    if (i >= brackets[0].left && i <= brackets[0].right) {
                        i = brackets[0].right+1;
                        resultList.push(setParenthesis(list.slice(brackets[0].left+1, brackets[0].right)));
                    }
                    if(i<list.length) {
                        resultList.push(list[i]);
                    }
                }
                return handleParenthesis(resultList)
            }
            return list;
        }

        function setParenthesis(list){
            var result={"type": "parenthesis", "expression": {}};
            if(list[0].type=="remoteService"){
                result.expression={"type":"remoteService","serviceCode":list[1],"params":[]};
                for(var i=2;i<list.length;i++){
                    result.expression.params.push(list[i]);
                }
            }else {
                result.expression = outParenthesis(list);
            }
            return result;
        }

        function outParenthesis(list){
            var methodList=[];
            var list1=[];
            var list2=[];
            var list3=[];
            var list4=[];

            for(var i=0;i<list.length;i++){
                var model = {};
                if(list[i].type=='lastDateTime'||list[i].type=='addHours'||list[i].type=='startWith'||list[i].type=='endsWith'||list[i].type=='matchWith'){
                    // model.type =list[i].type;
                    model=list[i];
                    model.source=list[i-1];
                    methodList.pop();
                    methodList.push(model);
                    list[i-1]=model;
                }else if(list[i].type=='compareHour'||list[i].type=='replaceDate'){
                    model=list[i];
                    model.source=list[i-1];
                    model.hours=list[i+1];
                    methodList.pop();
                    methodList.push(model);
                    list[i-1]=model;
                    list[i+1]=model;
                    i++;
                }else if(list[i].type=='compareHour'||list[i].type=='replaceDate'){
                    model=list[i];
                    model.source=list[i-1];
                    model.hours=list[i+1];
                    methodList.pop();
                    methodList.push(model);
                    list[i-1]=model;
                    list[i+1]=model;
                    i++;
                }else {
                    methodList.push(list[i]);
                }
            }
            for(var i=0;i<methodList.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(methodList[i].oper!=null&&(methodList[i].oper=="*"||methodList[i].oper=="/")){
                    model.oper=methodList[i].oper;
                    model.left=methodList[i-1];
                    model.right=methodList[i+1];
                    list1.pop();
                    list1.push(model);
                    methodList[i-1]=model;
                    methodList[i+1]=model;
                    i++;
                }else{
                    list1.push(methodList[i]);
                }
            }

            for(var i=0;i<list1.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list1[i].oper!=null&&(list1[i].oper=="+"||list1[i].oper=="-")){
                    model.oper=list1[i].oper;
                    model.left=list1[i-1];
                    model.right=list1[i+1];
                    list2.pop();
                    list2.push(model);
                    list1[i-1]=model;
                    list1[i+1]=model;
                    i++;
                }else{
                    list2.push(list1[i]);
                }
            }
            for(var i=0;i<list2.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list2[i].oper!=null&&(list2[i].oper=="<"||list2[i].oper==">"||list2[i].oper=="=="||list2[i].oper==">="||list2[i].oper=="<="||list2[i].oper=="!=")){
                    model.oper=list2[i].oper;
                    model.left=list2[i-1];
                    model.right=list2[i+1];
                    list3.pop();
                    list3.push(model);
                    list2[i-1]=model;
                    list2[i+1]=model;
                    i++;
                }else{
                    list3.push(list2[i]);
                }
            }
            for(var i=0;i<list3.length;i++){
                var model = {'oper':{},'left':{'type':'','value':''},'right':{'type':'','value':''}};
                if(list3[i].oper!=null&&(list3[i].oper=="&&"||list3[i].oper=="||")){
                    model.oper=list3[i].oper;
                    model.left=list3[i-1];
                    model.right=list3[i+1];
                    list4.pop();
                    list4.push(model);
                    list3[i-1]=model;
                    list3[i+1]=model;
                    i++;
                }else{
                    list4.push(list3[i]);
                }
            }
            return list4[0];
        }

        function checkRule(){
            var  errorMes= $("[name='errorMes']");
            for(var i=0;i<errorMes.length;i++){
                errorMes.remove();
            }
            var nodes = $("[name='rowVariable']");
            for(var i=0;i<nodes.length;i++){
                var typeList=[];
                var valueList=[];
                var idList=[];//通过匹配typeList 找出对应不符合要求的节点
                var spanNodes = nodes[i].children;
                //现将所有的type 放入到 list中，后续判断
                for(var j=0;j<spanNodes.length;j++){
                    /*spanNodes.attributes.type.nodeValue*/
                    var child =spanNodes[j].children;
                    if(child[0].attributes.type!=undefined&&child[0].attributes.value!=undefined) {
                        var type = child[0].attributes.type.nodeValue;
                        if(type!="button"&&child[0].attributes.value.nodeValue.indexOf("(")<0&&child[0].attributes.value.nodeValue.indexOf(")")<0) {
                            typeList.push(type);
                            idList.push(child[0].id);
                            valueList.push(child[0].attributes.value.nodeValue);
                        }
                    }
                }
                //根据上个步骤产生的typelist进行判断校验
                for(var j=0;j<typeList.length;j++){
                    if(j!=0){
                        //连续两个符号
                        if(typeList[j-1]==="sign"&&(typeList[j]==="sign"||typeList[j]==="method")){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        //连续两个变量、模型、输入值或方法后面跟这三个类型
                        else if(typeList[0]!=="setValue"&&(typeList[j-1]==="variable"||typeList[j-1]==="property"||typeList[j-1]==="entry")&&(typeList[j]==="variable"||typeList[j]==="property"||typeList[j]==="entry")){
                            var status="abnormal"
                            for(var i=0;i<j;i++){
                                if(typeList[i]=="component"){
                                    status="normal";
                                }
                            }
                            if(status=="abnormal"){
                                angular.element("#" + idList[j]).parent().parent().parent().append(
                                    "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                                );
                            }
                            break;
                        }
                        //设置变量或者属性时，不可连续三个属性或者变量等结合
                        if(j>1&&typeList[0]==="setValue"&&(typeList[j-2]==="variable"||typeList[j-2]==="property"||typeList[j-2]==="entry"||typeList[j-2]==="method")&&(typeList[j-1]==="variable"||typeList[j-1]==="property"||typeList[j-1]==="entry"||typeList[j-1]==="method")&&(typeList[j]==="variable"||typeList[j]==="property"||typeList[j]==="entry")){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        //设置变量与属性时，后面必须跟变量或者模型
                        if(typeList[0]==="setValue"&&typeList[1]!=="variable"&&typeList[1]!=="property"){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                        if(j==typeList.length-1){
                            if(typeList[j]=="sign"){
                                angular.element("#" + idList[j]).parent().parent().parent().append(
                                    "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                                );
                                break;
                            }
                        }
                    }else{
                        if(typeList[j]=="sign"){
                            angular.element("#" + idList[j]).parent().parent().parent().append(
                                "<div name='errorMes' class='infor-prompt'>表达式有误，请检查！</div>"
                            );
                            break;
                        }
                    }
                }
            }
        }
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.showEdit=function(type,state){
            var  leftBracketNodes= $("[name='leftBracket']");
            var  rightBracketNodes= $("[name='rightBracket']");
            var  attributeCheck = $(".attribute-check");
            //左右括号及节点高亮显示时不触发事件    不等于当前设置属性节点
            if(leftBracketNodes.length==0&&rightBracketNodes.length==0&&attributeCheck.length==0) {
                if (type == "node") {
                    var node = angular.element("#" + event.target.id);
                    if (event.target.tagName!="SPAN") {
                        node = node.parent();
                    }
                    node.removeClass();
                    node.addClass("attribute-on");

                    var childrenNode = node.children();
                    var childNode = angular.element("#" + childrenNode[0].id);
                    childNode.addClass("attribute-on-c");
                    var num = childNode.attr("id").replace("node", "");
                    childNode.after(
                        $compile(
                            "<div class='top' id='removeTop' ><a href='javascript:void(0)' ng-click='removeCondition(" + num + ")'>×</a></div>" +
                            "<div class='left' id='addLeft'><a href='javascript:void(0)' ng-click='addFront(" + num + ")'>＋</a></div>" +
                            "<div class='right' id='addRight'><a href='javascript:void(0)' ng-click='addBehind(" + num + ")'>＋</a></div>"
                        )($scope)
                    );
                }
            }
        };
        //type  按钮或者节点   state 编辑状态还是保存后状态，由于传入的节点不同，进行判断
        window.closeEdit=function(type,state){
            if(type=="node") {
                var node ;
                //当由右侧移出时，获取到的是a标签，其他获取到的是div，进行区别处理
                if(event.target.tagName=="A"&&(event.target.id==undefined||event.target.id=="")){
                    node = angular.element("#" + event.target.parentElement.id)
                }else {
                    node = angular.element("#" + event.target.id);
                }
                if(state=="edit"&&event.target.tagName!="SPAN"){
                    node = node.parent();
                }
                node.removeClass("attribute-on");
                var childrenNode =node.children();
                for (var i = 0; i < childrenNode.length; i++) {
                    var childNode = angular.element("#" + childrenNode[i].id);
                    if(i==0){
                        childNode.removeClass("attribute-on-c");
                    }else{
                        childNode.remove();
                    }
                }
            }
        };
        //添加括号方法
        $scope.addBracket=function(num){
            var nodesList=[];
            //$("#bracket").css("display", "block");
            var  rowNodes =$("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (nodesList[i].attributes.type.nodeValue == "property" || nodesList[i].attributes.type.nodeValue == "variable" || nodesList[i].attributes.type.nodeValue == "entry") {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + nodesList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='left' name ='leftBracket'><a href='javascript:void(0)' ng-click='addLeftBracket(&apos;" + nodesList[i].id + "&apos;)'>(</a></div>"
                            )($scope)
                        )
                    }
                }
            }
            showLeftBracket();
        };

        //点击左括号之后显示右括号
        function showRightBracket(nodeId){
            var nodesList=[];
            var startList=[];
            var  rowNodes= $("[name='rowC']");
            for(var i=0;i<rowNodes.length;i++){
                var divNodes = rowNodes[i].children;// <div>
                var spanNodes = divNodes[1].children; //<span>
                for(var j=0;j<spanNodes.length;j++){
                    var aNode = spanNodes[j].children;
                    nodesList.push(aNode[0]);
                }
            }
            for(var i=0;i<nodesList.length;i++){
                if(nodesList[i].id==nodeId){
                    startList=nodesList.slice(i,nodesList.length);
                    break;
                }
            }
            for(var i=0;i<startList.length;i++){
                if(nodesList[i].attributes.type!=undefined) {
                    if (startList[i].attributes.type!=undefined&&(startList[i].attributes.type.nodeValue == "property" || startList[i].attributes.type.nodeValue == "variable" || startList[i].attributes.type.nodeValue == "entry")) {
                        //nodesList[i].addClass("attribute-kuoh-c");
                        var node = angular.element("#" + startList[i].id);
                        node.parent().addClass("attribute-kuoh");
                        node.after(
                            $compile(
                                "<div class='right' name ='rightBracket'><a href='javascript:void(0)' ng-click='addRightBracket(&apos;" + startList[i].id + "&apos;)'>)</a></div>"
                            )($scope)
                        )
                    }
                }
            }
        }

        //添加左括号
        $scope.addLeftBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.before(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;(&apos;}'>(</a></span>"
                )($scope)
            );

            cleanBracket("left");
            showRightBracket(nodeId);
        };

        //添加右边括号
        $scope.addRightBracket= function(nodeId){
            $scope.countCondition++;
            var node =angular.element("#" + nodeId) ;
            var span = node.parent();
            span.after(
                $compile(
                    "<span  id='click" + $scope.countCondition + "'  onmouseleave='closeEdit(&apos;node&apos;)'  onmouseenter='showEdit(&apos;node&apos;)'  ><a href='javascript:void(0)' name='node'  id='node"+$scope.countCondition+"'  ng-click='show(&apos;"+$scope.countCondition+"&apos;,&apos;node&apos;,&apos;sign&apos;)'  type='sign' value='{&apos;oper&apos;:&apos;)&apos;}'>)</a></span>"
                )($scope)
            );

            cleanBracket("right");
            closeDiv();
        };

        function showLeftBracket(){
            $("#shadeCondition").css({ display: "block"});
            $("#bracket").css("display", "block");
        }

        function showDIV() {
            $("#shadeCondition").css({ display: "block"});
        }
        function closeDiv() {
            $("#shadeCondition").css({ display: "none"});
        }

        //type: left | right | all
        function cleanBracket(type){
            if(type=="left"||type=="all"){
                var  bracketNodes= $("[name='leftBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
            if(type=="right"||type=="all"){
                var  bracketNodes= $("[name='rightBracket']");
                for(var i=0;i<bracketNodes.length;i++){
                    bracketNodes[i].remove();
                }
            }
        }

        //点击遮罩还原
        $("#shadeCondition").mouseup(function(){
            init();
            closeDiv();
            cleanBracket("all");
            angular.element("#node" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).removeClass("attribute-check");
            angular.element("#showCondition" + $scope.nowClick).html("点击选择");
        });
        //符号转中文显示
        function  translateMes(value) {
            var mes;
            angular.forEach($scope.translate, function (data) {
                for (var key in data) {
                    if (key == value) {
                        mes = data[key];
                        break;
                    }
                }
            });
            return mes;
        }
        $scope.showHours=function(){
            $scope.addHourTime=true;
        };
        $scope.closeHours=function(){
            $scope.addHourTime=false;
        };

        $scope.selectAttr=function(attr){
            angular.element("#addHours").attr("value",attr.name);
            angular.element("#addHours").text(attr.name);
            $scope.addHourTime=false;

        }

    }]);
    return app;
});